package com.ht.reeducation.jobTask;

import com.csvreader.CsvReader;
import com.ht.reeducation.dao.VehicleDao;
import com.ht.reeducation.entity.Vehicle;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.ibatis.annotations.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
//@EnableScheduling
public class JobTask {

    private static Logger log = LoggerFactory.getLogger(JobTask.class);
    /**
     *
     */
    @Autowired
    private VehicleDao vehicleDao;

    //每天00：40分钟执行从csv中取数据，将数据插入到指定数据库
    //时间需要2个半小时左右
    @Scheduled(cron = "0 40 0 * * ?")
    //@Scheduled(cron = "0 * * * * ?") 立即执行
    private void doMysql() {
        FtpUtils Uftp = new FtpUtils();

        FTPClient ftp = Uftp.loginftp("192.168.233.248", "111111", "vehicle", 21);
        //FtpUtils ftpU = new FtpUtils();
        uploadFtp(ftp);
        Uftp.ftpLogOut(ftp);
    }

    public void uploadFtp(FTPClient ftp) {
        Vehicle vehicle = new Vehicle();
        ArrayList<Vehicle> selectvehicleList = new ArrayList<>();
        //ArrayList<Vehicle> insertvehicleList = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dirname = df.format(new Date());
        String fileName = "non_yt_vehicle.csv";
        try {
            if (null != ftp) {
                ftp.changeWorkingDirectory(dirname);
                FTPFile[] file = ftp.listFiles();
                for (int i = 0; i < file.length; i++) {
                    if (file[i].getName().contains(fileName)) {
                        // 将匹配到的文件流传入接口，转化成数组集合
                        ArrayList<String[]> csvList = csv(ftp.retrieveFileStream(file[i].getName()));
                        // 将csv文件里的数据打印出来
                        // 遍历每一行
                        for (int row = 0; row < csvList.size(); row++) {
                            // 遍历每一行中的每一列
                            for (int j = 0; j < csvList.get(row).length; j++) {
                                //System.out.print(csvList.get(row)[j]);
                                String[] splitCsv = csvList.get(row)[j].split("\t");
                                vehicle.setHphm(splitCsv[0]);
                                vehicle.setHpzl(splitCsv[1]);
                                vehicle.setHphm_first(splitCsv[2]);
                                vehicle.setHphm_top_two(splitCsv[3]);
                                vehicle.setRksj(splitCsv[4]);
                                vehicle.setGxsj(splitCsv[5]);
                                vehicle.setClzt(splitCsv[6]);
//                                System.out.println(vehicle.getHphm());
//                                System.out.println(vehicle.getHpzl());
//                                System.out.println(vehicle.getHphm_first());
//                                System.out.println(vehicle.getHphm_top_two());
//                                System.out.println(vehicle.getRksj());
//                                System.out.println(vehicle.getGxsj());
//                                System.out.println(vehicle.getClzt());
                                selectvehicleList = vehicleDao.selectNonYtCar(vehicle);
                                //System.out.println("selectvehicleList================================="+selectvehicleList);
                                //System.out.println("selectvehicleList===========size=================="+selectvehicleList.size());

                                if (selectvehicleList==null || selectvehicleList.size() == 0) {
                                    int insertvehicle = vehicleDao.insertVehicle(vehicle);
                                    log.info("插入成功--------号牌号码为" + vehicle.getHphm() + "--号牌种类为" + vehicle.getHpzl());
                                } else {
                                    int updatevehicle = vehicleDao.updateVehicle(vehicle);
                                    log.info("更新成功--------号牌号码为" + vehicle.getHphm() + "--号牌种类为" + vehicle.getHpzl() + "--更新时间为" + vehicle.getGxsj());
                                }
                            }
                            System.out.println("--------------------------------------------------------------");
                        }

                    }
                }
            }
        } catch (Exception e) {
            log.error("Exception(ftp)---error: " + e.getMessage() + "\t\n" + e + "\t\n", e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * <b>将一个IO流解析，转化数组形式的集合<b>
     *
     * @param in 文件inputStream流
     */
    public ArrayList<String[]> csv(InputStream in) {
        ArrayList<String[]> csvList = new ArrayList<String[]>();
        if (null != in) {
            CsvReader reader = new CsvReader(in, ',', Charset.forName("UTF-8"));
            try {
                //遍历每一行，若有#注释部分，则不处理，若没有，则加入csvList
                while (reader.readRecord()) {
                    if (!reader.getValues()[0].contains("#"))// 清除注释部分
                    {
                        //获取的为每一行的信息，以数组的形式
                        csvList.add(reader.getValues());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            reader.close();
        }
        return csvList;
    }
}
